<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <th:block th:include="common/head::head"></th:block>
    <style>
        body {
            position: absolute;
            top: 0px;
            right: 0px;
            bottom: 0px;
            left: 0px;
            padding: 10px;
        }

        .console {
            height: 100%;
            position: relative;
        }

        .console .terminal {
            position: absolute;
            top: 40px;
            right: 0px;
            bottom: 0px;
            left: 0px;
            border: 1px solid #c1c1c1;
            border-radius: 5px;
            font-family: Consolas;
            padding: 5px;
            overflow: auto;
            word-break: keep-all;
            white-space: nowrap;
        }

        .console .status {
            display: inline-block;
            float: right;
        }

        .console .status .status-div {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            border: 1px solid #c1c1c1;
        }

        .console .status .status-run {
            background-color: #05ff2d;
        }

        .console .status .status-stop {
            background-color: #ff0000;
        }
    </style>
</head>

<body>
<div class="console">
    <div class="layui-row" id="optDiv">
        <!-- layui-elem-quote -->
        <a href="javascript:;" class="btn-op layui-btn  layui-btn-sm" op="start">执行</a>
        <!--         <a href="javascript:;" class="btn-op layui-btn  layui-btn-sm layui-btn-warm" op="restart">重启</a>-->
        <a href="javascript:;" style="display: none;" class="btn-op layui-btn  layui-btn-sm layui-btn-danger"
           op="stop">停止</a>

        <div class="status">
            <div class="status-div"></div>
            <span></span>
        </div>
    </div>
    <div class="terminal"></div>
</div>
</body>
<script type="text/javascript">
    var heart;
    var scriptId = getQueryString("id");

    function loadSuccess() {
        const showLogDom = $('.console .terminal');

        if ('WebSocket' in window) {
            var url = getSocketHost() + "/script_run?userId=[[${session.user.getUserMd5Key()}]]&scriptId=" + scriptId + "&nodeId=[[${node.id}]]&type=script";
            const ws = new WebSocket(url);
            ws.onopen = function () {
                showLogDom.append('WebSocket连接成功！<br/>');
            };

            ws.onmessage = function (data) {
                // 如果是
                if (data.data.indexOf('{') === 0) {
                    layer.closeAll();
                    var json_data = null;
                    try {
                        json_data = JSON.parse(data.data);
                    } catch (e) {
                        showLogDom.append(data.data + '<br/>');
                        return;
                    }
                    if (json_data.code !== 200) {
                        layer.msg(json_data.msg);
                    }
                    showLogDom.append(json_data.msg + (json_data.data || "") + '<br/>');
                    var op = json_data.op;
                    switch (op) {
                        case 'start':
                            if (200 === json_data.code) {
                                $('.status .status-div').removeClass('status-stop').addClass('status-run');
                                $('.status span').text('运行中');
                                setOpBtn(false);
                            } else {
                                $('.status .status-div').removeClass('status-run').addClass('status-stop');
                                $('.status span').text(json_data.msg);
                                setOpBtn(true);
                            }
                            break;
                        case 'stop':
                            if (200 === json_data.code) {
                                $('.status .status-div').removeClass('status-run').addClass('status-stop');
                                $('.status span').text('未运行');
                                setOpBtn(true);
                            } else {
                                $('.status span').text(json_data.msg);
                            }
                            break;
                        default:
                            break;
                    }
                } else {
                    if (data.data) {
                        showLogDom.append(data.data + '<br/>');
                    }
                    clearInterval(heart);
                    // 创建心跳，防止掉线
                    heart = setInterval(function () {
                        const data = {
                            op: "heart",
                            scriptId: scriptId
                        };
                        ws.send(JSON.stringify(data));
                    }, 5000);
                }
                scrollToBotomm();
            };

            ws.onclose = function (er) {
                showLogDom.append('WebSocket连接已关闭！<br/>');
                clearInterval(heart);
                $("#optDiv").hide();
                layer.alert("控制台已离线")
            };

            $('.btn-op').on('click', function () {
                var op = $(this).attr('op');
                if (op == "stop") {
                    layer.confirm("确定要停止该脚本吗？", {
                        title: '系统提示'
                    }, function (index) {
                        layer.close(index);
                        setMsg(op);
                    });
                } else if (op == "start") {
                    //
                    layer.prompt({
                        title: '请输入执行参数',
                        formType: 2,
                        value: ' '
                    }, function (text, index) {
                        layer.close(index);
                        showLogDom.html("");
                        setMsg(op, text);
                    });
                }
            });

            function setMsg(opt, args) {
                const data = {
                    op: opt,
                    scriptId: scriptId,
                    args: args
                };
                layer.load(1, {
                    shade: [0.3, '#fff']
                });
                ws.send(JSON.stringify(data));
                setTimeout(function () {
                    layer.closeAll('loading');
                }, 2000);
            }
        } else {
            showLogDom.html('你的浏览器不支持WebSocket！');
        }

        function setOpBtn(flag) {
            if (flag) {
                $('.btn-op[op="start"]').show();
                $('.btn-op[op="stop"]').hide();
            } else {
                $('.btn-op[op="start"]').hide();
                $('.btn-op[op="stop"]').show();
            }
        }

        function scrollToBotomm() {
            var h = showLogDom[0].scrollHeight;
            // if (window.screen.height * 2 < h) {
            //     showLogDom.html("已清空屏幕缓存" + '<br/>');
            //     showLogDom.scrollTop(0);
            //     return;
            // }
            showLogDom.scrollTop(h);
        }

    }

</script>
</html>